package com.wzh.test;

/**
 * 五个小孩围着坐
 * 从第一个开始数数
 * 数到2的就退出
 * 求 退出的编号顺序
 */
public class CircleSingleLinkedListDemo {
    public static void main(String[] args) {
        CircleSingleLinkedList list = new CircleSingleLinkedList(5);
        //list.print();

        list.popOut(2);
    }
}

class CircleSingleLinkedList{
    private CNode first;
    private CNode last;
    public CircleSingleLinkedList(int num){
        for(int i = 1; i <= num;i++){
            CNode node = new CNode(i);
            if(i == 1){
                first = node;
                last = node;
            }else{
                last.setNext(node);
                last = node;
                last.setNext(first);
            }
        }
    }

    public void popOut(int space){
        CNode currentNode = first;
        CNode prevNode = null;
        int count = 1;
        while (true){
            prevNode = currentNode;
            currentNode = currentNode.getNext();
            count++;
            if(count == space){
                //出列
                System.out.println(currentNode);
                if(prevNode == currentNode){
                    break;
                }
                prevNode.setNext(currentNode.getNext());
                currentNode = currentNode.getNext();
                count = 1;

            }

        }

    }
    public void print(){
        CNode currentNode = first;
        while (true){
            System.out.println(currentNode);
            currentNode = currentNode.getNext();
            if(currentNode == first){
                break;
            }
        }
    }
}

class CNode{
    private int no;
    private CNode next;

    public CNode(int no) {
        this.no = no;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public CNode getNext() {
        return next;
    }

    public void setNext(CNode next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return "CNode{" +
                "no=" + no +
                '}';
    }
}
